package com.netolobo.blospot.crud;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;

public class DbAdapter {

	// string para criação do banco, serão os nomes das tabelas
	public static final String KEY_NAME = "name";
	public static final String KEY_TIME = "time";
	public static final String KEY_ROWID = "_id";

	private static final String TAG = "DbAdapter";// usado no log
	private DatabaseHelper mDbHelper;
	private SQLiteDatabase mDb;

	// String de criação do banco

	private static final String DATABASE_CREATE = "create table records (_id integer primary key autoincrement, "
			+ "name text not null, time text not null);";

	private static final String DATABASE_NAME = "records";
	private static final String DATABASE_TABLE = "records";// A DATABASE_TABLE tem que ter o mesmo nome da tabela criada nome DATABASE CREATE
	// nesse caso viagens
	
	private static final int DATABASE_VERSION = 2;

	private final Context mCtx;

	private static class DatabaseHelper extends SQLiteOpenHelper {

		DatabaseHelper(Context context) {
			super(context, DATABASE_NAME, null, DATABASE_VERSION);
		}

		@Override
		public void onCreate(SQLiteDatabase db) {

			db.execSQL(DATABASE_CREATE);
			Log.w(TAG, "Criando o banco");
		}

		@Override
		public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
			Log.w(TAG, "Atualizando o banco de dados da versão " + oldVersion
					+ " para " + newVersion
					+ ", que irá apagar todos dados antigos");
			db.execSQL("DROP TABLE IF EXISTS traveller");
			onCreate(db);
		}
	}

	/**
	 * Construtor - leva o contexto para permitir que o banco de dados seja
	 * Aberto / criado
	 * 
	 * @param ctx é o Context com qual ela trabalha
	 */
	public DbAdapter(Context ctx) {
		this.mCtx = ctx;
	}

	/**
	 * Open the notes database. If it cannot be opened, try to create a new
	 * instance of the database. If it cannot be created, throw an exception to
	 * signal the failure
	 * 
	 * @return this (self reference, allowing this to be chained in an
	 *         initialization call)
	 * @throws SQLException
	 *             if the database could be neither opened or created
	 */
	public DbAdapter open() throws SQLException {
		mDbHelper = new DatabaseHelper(mCtx);
		mDb = mDbHelper.getWritableDatabase();
		return this;
	}

	public void close() {
		mDbHelper.close();
	}

	
	public void createRecord(String name, int numeroJogadas) {
		
		ContentValues initialValues = new ContentValues();
		initialValues.put(KEY_NAME, name);
		initialValues.put(KEY_TIME, numeroJogadas);
		
		mDb.insert(DATABASE_TABLE, null, initialValues);
		
				
	}

	/**
	 * Deleta o recorde de acordo com o id passado
	 * @param rowId
	 * @return
	 */
	 
	public boolean deleteRecord(long rowId) {

		return mDb.delete(DATABASE_TABLE, KEY_ROWID + "=" + rowId, null) > 0;
	}

	/**
	 * Return a Cursor over the list of all records in the database
	 * 
	 * @return Cursor over all records
	 */
	public Cursor fetchAllRecords() {
		Cursor mCursor = mDb.query(DATABASE_TABLE, new String[] { KEY_ROWID, KEY_NAME, KEY_TIME }, null, null, null,
				null, null);
		
		/*if (mCursor != null) {
			mCursor.moveToFirst();
		}*/
		
		return mCursor;
				
	}

	/**
	 * Return a Cursor positioned at the records that matches the given rowId
	 * 
	 * @param rowId
	 *            id of note to retrieve
	 * @return Cursor positioned to matching note, if found
	 * @throws SQLException
	 *             if note could not be found/retrieved
	 */
	public Cursor fetchRecord(long rowId) throws SQLException {//talvez não será usado

		Cursor mCursor =

		mDb.query(true, DATABASE_TABLE, new String[] { KEY_ROWID, KEY_NAME, KEY_TIME},
				KEY_ROWID + "=" + rowId, null, null, null, null, null);
		if (mCursor != null) {
			mCursor.moveToFirst();
		}
		return mCursor;

	}

	
	/** Atualiza o record de acordo com o id, name e time passados
	 * 
	 * @param rowId
	 * @param name
	 * @param time
	 * @return
	 */
	public boolean updateNote(long rowId, String name, String time) {
		ContentValues args = new ContentValues();
		args.put(KEY_NAME, name);
		args.put(KEY_TIME, time);			

		return mDb.update(DATABASE_TABLE, args, KEY_ROWID + "=" + rowId, null) > 0;
	}

}

